/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rest.jbpm.task;

import java.util.ArrayList;
import java.util.List;
import org.hibernate.*;
import org.hibernate.criterion.Restrictions;
import org.jbpm.api.cmd.Command;
import org.jbpm.api.cmd.Environment;
import org.jbpm.api.identity.User;
import org.jbpm.api.task.Task;
import org.jbpm.pvm.internal.task.TaskImpl;
import org.jbpm.pvm.internal.util.CollectionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rest.jbpm.identity.FindUsersByGroupCmd;
import rest.jbpm.services.DNC14N;

/**
 *
 * @author jump
 */
public class FindCoWorkerslTasksUnwrapped implements Command<List<Task>> {
    
    private static final Logger log = LoggerFactory.getLogger(FindCoWorkerslTasksUnwrapped.class);
    private final String group;
    
    public FindCoWorkerslTasksUnwrapped(String group) {
        this.group = group;
    }
            
    @Override
    public List<Task> execute(Environment environment) throws Exception {
        
        Session session = null;
        SessionFactory sessionFactory = environment.get(SessionFactory.class);
        log.info("getting co-worker's tasks for {}",group);
        
        try {
            
            List<User> users = new FindUsersByGroupCmd(group).execute(environment);
            if(users == null) return null;
                
            if(users.isEmpty()) return new ArrayList<Task>();
            
            List<String> names = new ArrayList<String>();
            
            for(User u : users)
                names.add(DNC14N.c14n(u.getId()));
            
            session = sessionFactory.openSession();
            
            List<Task> tasks = session.createCriteria(TaskImpl.class, "task")
                    .add(
                        Restrictions.and(
                            Restrictions.in("assignee",names),
                            Restrictions.eq("state", Task.STATE_OPEN)))
                    .setFetchMode("execution", FetchMode.JOIN)
                    .setFetchMode("execution.variables", FetchMode.JOIN)
                    .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
                    .setFirstResult(0).list();
            
            log.info("{} tasks found",tasks.size());            
            
            return CollectionUtil.checkList(tasks,Task.class);
            
        } finally {
            if(session != null) session.close();
        }
    }
    
}
